import { Spin } from "@arco-design/web-react";
import { IconPlayArrow, IconRecordStop } from "@arco-design/web-react/icon";
import React, { useCallback, useEffect, useRef, useState } from "react";
import styled from './audio.module.less'
import { VisualAudio } from "./visualAudio";


export interface IAudioCanvas {
    playList: string[];
}

function AudioCanvas(props: IAudioCanvas) {

    const { playList } = props;

    const [ isLoading, setIsLoading ] = useState<boolean>(true);
    const canvasRef = useRef<HTMLCanvasElement>(null);
    const audioRef = useRef<HTMLAudioElement>(null);

    const useAudio = (): any => {

        const [adState, setAdState] = useState('play');
        // 暂停和播放
        const pauseOrStart = useCallback(() => {

            const target = audioRef.current;
            switch (adState) {
                case 'play':
                    setAdState('pause');
                    target?.play();
                    break;
                case 'pause':
                    setAdState('play');
                    target?.pause();
            }
        }, [adState]);

        // 同步
        const synchro = (media) => {

            const target = audioRef.current;
            if (target) {
                setIsLoading(true);
                setAdState('play');
                target.src = media;
                target.oncanplay = (e) => {
                    setIsLoading(false);
                    setAdState('pause');
                }
                target.load();
                console.log('同步最新音频')
            }
        };

        return [adState, pauseOrStart, synchro, setAdState]
    }

    const [adState, pauseOrStart, synchro, setAdState] = useAudio();


    useEffect(() => {

        // 初始化可视化音频对象
        let vAudio: null | VisualAudio = null;

        // 监听节点的变化
        let observer: null | ResizeObserver = null;

        const onFinish = () => {
            // 全部播放完了则设置为 停止播放的按钮状态
            setAdState('play');
        };
        
        if (playList.length > 0) {
            navigator?.mediaDevices?.getUserMedia({ audio: true }).then(() => {
                vAudio = new VisualAudio(canvasRef, audioRef, playList);
                observer = new ResizeObserver(() => { vAudio?.resize() });
                vAudio.open();
                observer.observe(vAudio.__canvas.__ref);
                setIsLoading(false);
                vAudio.addEventListener('finish', onFinish)
                console.log('audio opened');
            })
        }
        
        return () => {
            if (playList.length > 0 && vAudio && observer) {
                console.log('audio closed');
                vAudio.removeEventListener('finish', onFinish);
                observer.unobserve(vAudio.__canvas.__ref);
                observer.disconnect();
                vAudio.close();
            }
        }

    }, [ playList ])
    
    return (
        <div className={ styled['audio-wrapper'] }>
            {
                isLoading ?
                <div className={ styled['canvas-mantle'] }>
                    <Spin dot></Spin>
                </div> : ''
            }
            <canvas ref={canvasRef} className={styled['audio-img']} />
            <audio ref={audioRef} crossOrigin="anonymous">
                Your browser does not support the audio tag.
            </audio>
            <div className={styled['audio-btn']}>
                {/* 播放暂停 */}
                <div className={`${styled['btnIcon']}`} onClick={pauseOrStart}>
                    {
                        adState === 'play' ? <IconPlayArrow /> : <IconRecordStop /> 
                    }
                </div>
            </div>

            {/* 缺乏多个间断音频的衔接功能 */}
        </div>
    )
}

export default AudioCanvas